package com.liu.webstore.config;

import com.liu.webstore.common.Constant;
import com.liu.webstore.util.WebstoreUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author LiuYumei
 * @Date 2022/8/21 22:04
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(
                        "/user/setting",
                        "/user/upload",
                        "/discuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/notice/**",
                        "/like",
                        "/follow",
                        "/unfollow"
                )
                .hasAnyAuthority(
                        Constant.AUTHORITY_USER,
                        Constant.AUTHORITY_ADMIN,
                        Constant.AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/post",
                        "/discuss/wonderful"
                )
                .hasAnyAuthority(
                        Constant.AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/delete",
                        "/data/**"
                )
                .hasAnyAuthority(
                        Constant.AUTHORITY_ADMIN
                )
                // 除了以上拦截的路径外，其他路径都允许
                .anyRequest().permitAll()
                .and().csrf().disable();

        http.exceptionHandling()
                // 没有登录时的处理
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        String xRequestedWith = request.getHeader("x-requested-with");
                        // 异步请求
                        if (Constant.XML_HTTP_REQUEST.equals(xRequestedWith)) {
                            response.setContentType("application/plain;charset=utf-8");
                            // 向前台输出内容
                            PrintWriter writer = response.getWriter();
                            writer.write(WebstoreUtil.getJsonString(403, "你还没有登录！"));
                        } else {
                            // 同步请求
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                })
                // 权限不够时的处理
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        String xRequestedWith = request.getHeader("x-requested-with");
                        // 异步请求
                        if (Constant.XML_HTTP_REQUEST.equals(xRequestedWith)) {
                            response.setContentType("application/plain;charset=utf-8");
                            // 向前台输出内容
                            PrintWriter writer = response.getWriter();
                            writer.write(WebstoreUtil.getJsonString(403, "你没有访问此功能的权限！"));
                        } else {
                            // 同步请求
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                });

        // security底层默认拦截/logout请求，进行退出处理。覆盖它默认的逻辑，执行自己的退出逻辑
        http.logout().logoutUrl("/security/logout");

    }
}
